package com.byxy.managerial.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;

import com.byxy.managerial.dao.DepartmentDao;
import com.byxy.managerial.entity.Department;

/**
 * 部门dao接口实现类
 * 
 * @author muxiangling
 *
 */

@SuppressWarnings("unchecked")
@Repository
public class DepartmentDaoImpl implements DepartmentDao {
	/**
	 * 获取工厂方法
	 */
	@Resource
	private SessionFactory sessionFactory;

	/**
	 * 增加部门方法
	 */
	@Override
	public void save(Department e) {
		sessionFactory.getCurrentSession().save(e);
	}

	/**
	 * 删除部门方法
	 */
	@Override
	public void delete(Department e) {
		sessionFactory.getCurrentSession().delete(e);
	}

	/**
	 * 修改部门方法
	 */
	@Override
	public void update(Department e) {
		sessionFactory.getCurrentSession().clear();
		sessionFactory.getCurrentSession().update(e);
	}

	/**
	 * 查询所有部门方法
	 */
	@Override
	public List<Department> find() {
		String sql = "from " + Department.class.getSimpleName();
		return sessionFactory.getCurrentSession().createQuery(sql).list();
	}

	/**
	 * 分页查询部门方法
	 */
	@Override
	public List<Department> find(int pos, int row) {
		String sql = "from " + Department.class.getSimpleName();
		return sessionFactory.getCurrentSession().createQuery(sql).setFirstResult(pos).setMaxResults(row).list();
	}

	/**
	 * 根据id查询部门方法
	 */
	@Override
	public Department getByID(Serializable id) {
		return (Department) sessionFactory.getCurrentSession().get(Department.class, id);
	}

	/**
	 * 统计部门数量方法
	 */
	@Override
	public long countAll() {
		String sql = "select count(u) from " + Department.class.getSimpleName() + " u";
		return (long) sessionFactory.getCurrentSession().createQuery(sql).uniqueResult();
	}

	/**
	 * 根据部门名称查询部门的方法
	 */
	@Override
	public Department getByName(String name) {
		String hql = "from " + Department.class.getSimpleName() + " where dname = ?";
		List<Department> list = sessionFactory.getCurrentSession().createQuery(hql).setParameter(0, name).list();
		Department department = null;
		if (list.size() != 0) {
			department = list.get(0);
		}
		return department;
	}

	/**
	 * 模糊查询部门信息
	 */
	@Override
	public List<Department> findDim(String likeVal) {
		// 原生sql语句
		String sql = "select * from m_department where concat(id,depint,dname,dprincipal) like '%" + likeVal
				+ "%'";
		// 执行原生sql语句方法,将绑定给addEntity(Department.class)
		Query query = sessionFactory.getCurrentSession().createSQLQuery(sql).addEntity(Department.class);
		return query.list();
	}

}
